/**
 * Created by Administrator on 2017/5/1.
 */
var submitElement=document.getElementById('submit');
var messageElement=document.getElementById('message');
var formElement=document.getElementById('myForm');
submitElement.onclick = function () {
    var elementUsername = document.querySelector('#myForm input[name=username]');
    var username = elementUsername.value;
    if (username == '') {
        messageElement.innerHTML='用户名不能为空！';
        return;
    }

    var passwordElement = document.querySelector('#myForm input[name=password] ');
    var password = passwordElement.value;
    if (password == '') {
        messageElement.innerHTML='密码不能为空！';
        return;
    }

    var str = password;
    if(!str.match(/^\d{6}$/)) {
        messageElement.innerHTML = '请输入6位数字密码';
        return;
    }

    var confirmElement = document.querySelector('#myForm input[name=confirm] ');
    var confirm = confirmElement.value;
    if (confirm == '') {
        messageElement.innerHTML='确认密码不能为空！';
        return;
    }

    if(password!=confirm){
        messageElement.innerHTML='密码不一致！';
        return;
    }

    var nicknameElement = document.querySelector('#myForm input[name=nickname] ');
    var nickname = nicknameElement.value;
    if (nickname == '') {
        messageElement.innerHTML='昵称不能为空！';
        return;
    }
    var dateElement = document.querySelector('#myForm input[name=date] ');
    var birthday = dateElement.value;
    if (birthday == '') {
        messageElement.innerHTML='出生年月不能为空！';
        return;
    }

    var str = birthday;
    if(!str.match(/^[\d]{4}[-][\d]{1,2}[-][\d]{1,2}$/)) {
        messageElement.innerHTML='出生年月格式错误！';
        return;
    }

    var sexElement = document.querySelector('#myForm input[name=sex]:checked ');
    var sex = sexElement.value;

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {   //等待远程主机做出回应
        if (this.readyState == 4) {
            if (this.status == 200) {
                var result=JSON.parse(this.responseText);
                if(result.error==1){
                    messageElement.innerHTML=result.message;
                }else {
                    messageElement.innerHTML='注册成功！';
                    location.href='../Login.php';
                }
            } else {
                alert('服务器出现异常，请及时联系管理员')
            }
        }
    };
    xhr.open( formElement.method,formElement.action);
    var data=new FormData();
    data.append('username',username);
    data.append('password',password);
    data.append('confirm',confirm);
    data.append('nickname',nickname);
    data.append('birthday',birthday);
    data.append('sex',sex);
    console.log(data);
    xhr.send(data);
};